<style scoped>
.footer {
  background-color: white;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.footer-content {
  height: 100%;
  margin-left: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.a-left {
  display: flex;
  align-items: center;
  margin-left: 2%;
  text-decoration: none;
  color: black
}

.a-right {
  margin-left: 2%;
  text-decoration: none;
  color: black
}

.a-right:hover,
.a-left:hover {
  color: blue;
}
</style>

<template>
  <!--    <div style="position: fixed; z-index: -1; width: 100%; height: 100%">-->
  <!--      <video autoplay loop muted style="width: 100%; height: 100%; object-fit: cover;">-->
  <!--        <source src="../assets/mp4/login.mp4" type="video/mp4">-->
  <!--      </video>-->
  <!--    </div>-->
  <div style="display: flex;height: 100vh;align-items: center;justify-content: center;">
    <!--  background-color: rgba(255, 255, 255, 0.5);  -->
    <div style="display: flex;width: 50%;height: 60vh;border-radius: 5px;overflow: hidden;background-color: white">
      <!-- 图片 -->
      <div style="flex: 1;display: flex;justify-content: center;align-items: center;">
        <img style="width: 100%;" src="../assets/img/login.png" alt="">
      </div>
      <!-- 表单 -->
      <div style="flex: 1;display: flex;justify-content: center;align-items: center;flex-direction: column;">
        <div style="width: 100%;font-size: 20px;font-weight: bold;text-align: center;margin-top: 35px">欢迎登录招投标文件管理系统
        </div>

        <!--   添加一个 @keyup.enter 事件监听器,按下回车键触发登录事件     -->
        <el-form :model="data.user" style="width: 80%;height: 75%;padding-top: 10px;" :rules="data.rules"
                 ref="ruleFormRef" @keyup.enter="clickLogin">

          <el-form-item style="margin-top: 25%;box-sizing: border-box" prop="username">
            <el-input size="large"  :prefix-icon="Avatar" placeholder="请输入账号" v-model="data.user.username"></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input size="large" :prefix-icon="Lock" show-password placeholder="请输入密码"
                      v-model="data.user.password"></el-input>
          </el-form-item>

          <el-form-item prop="InputValidCode">
            <el-input style="flex: 1;" size="large" :prefix-icon="CircleCheck" placeholder="请输入验证码"
                      v-model="data.user.InputValidCode"></el-input>
            <div style="flex: 1;">
              <ValidCode @input="getValidCode"/>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button :disabled="!data.isFormValid"
                       type="primary"
                       style="width: 100%;"
                       @click="clickLogin"
                       :loading="data.loading">登 录</el-button>
          </el-form-item>
        </el-form>

        <div style="display: flex;justify-content: space-around;width: 100%;box-sizing: border-box">
          <div>没有账号？请 <span style="color: #409eff;cursor: pointer;" @click="$router.push('/register')">注册</span></div>
          <div style="color: #409eff;cursor: pointer;text-align: right;" @click="$router.push('/findPassword')">忘记密码
          </div>
        </div>
      </div>
    </div>
  </div>
  <el-footer class="footer">
    <div class="footer-content">
      <span>©2024 ldystudy.cn 版权所有</span>
      <a target="_blank" class="a-left"
         href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=52262202000037">
        <img src="/备案图标.png" style="float:left;height: 50%;"/>
        <p>
          贵公网安备 52262202000037号
        </p>
      </a>
      <a class="a-right" href="https://beian.miit.gov.cn" target="_blank">工信部备案：黔ICP备2023009910号</a>
    </div>
  </el-footer>
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';
import {Avatar, CircleCheck, Lock} from '@element-plus/icons-vue';
import ValidCode from "@/components/ValidCode.vue";
import {useRouter} from "vue-router";
import request from "../utils/request.js";

const ruleFormRef = ref(null);

const data = reactive({
  isFormValid: false, // 新增：用于控制表单是否有效，进而控制按钮的启用/禁用
  user: {
    // username: 'Uuser123',
    // password: 'Uuser123',
    // username: 'Aadmin123',
    // password: 'Aadmin123',
    username: '',
    password: '',
    InputValidCode: '', // 用户输入的验证码
    loading: false, // 控制登录按钮的loading状态
  },
  rules: {
    username: [
      {required: true, message: "请输入账号", trigger: "blur"},
      {min: 8, max: 20, message: "账号长度为[8-20]", trigger: "blur"},
      {pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,20}$/, message: "账号必须同时含有大小写字母和数字", trigger: "blur"}
    ],
    password: [
      {required: true, message: "请输入密码", trigger: "blur"},
      {min: 8, max: 20, message: "密码长度为[8-20]", trigger: "blur"},
      {pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,20}$/, message: "密码必须同时含有大小写字母和数字", trigger: "blur"}
    ],
    InputValidCode: [ // 验证码的校验规则
      {required: true, message: "请输入验证码", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (value.toLowerCase() !== data.validCode.toLowerCase()) {
            callback(new Error('验证码错误'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
  },
  validCode: '', // 系统生成的验证码
  loading: null,
});

//  新增一个方法，用于检验表单，并更新表单验证状态
const validateForm = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.validate(valid => {
      data.isFormValid = valid; // 更新表单的验证状态
    });
  }
};

// 监听data.user对象的变化，以便及时校验表单
watch(() => data.user, validateForm, {deep: true, immediate: true});

// 从ValidCode组件中获取验证码
const getValidCode = (code) => {
  data.validCode = code;
};

// 设置loading状态
const setLoading = (value) => {
  data.loading = value;
};

// 点击登录按钮进行表单验证和登录
const router = useRouter();
const clickLogin = () => {
  const form = ruleFormRef.value;
  if (form) {
    form.validate((valid) => {
      if (valid) {
        setLoading(true); // 开始登录，按钮显示加载状态
        const loginData = {
          username: data.user.username,
          password: data.user.password
        };
        request.post("/login", loginData).then(async (response) => {
          setLoading(false); // 登录结束，按钮移除加载状态
          // 登录成功的操作，例如保存token
          if (response.code === 200) {
            ElMessage.success('客户端提示：登录成功');
            const userRolesResponse = await request.get(`/user/getUserRolesDetailByUsername?username=${data.user.username}`);
            localStorage.setItem('data', JSON.stringify(userRolesResponse));
            localStorage.setItem('userRoles', JSON.stringify(userRolesResponse.roles.split(',').map(role => role.trim())));
            localStorage.setItem("password", data.user.password);
            router.push("/index")// 登录成功后进行页面跳转
          } else {
            ElMessage.error('客户端提示：用户名或密码错误');
          }
        }).catch((error) => {
          setLoading(false); // 登录结束，按钮移除加载状态
          ElMessage.error('客户端提示：' + error.message);
        });
      }
    });
  }
};

// 确保组件加载时进行一次表单验证
onMounted(() => {
  validateForm();
});

</script>